package com.example.mapdsl;

import com.example.mapdsl.dsl.MapDSLLexer;
import com.example.mapdsl.dsl.MapDSLParser;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

public class MapDSLMain {
    public static void main(String[] args) {
        try {
            // 准备测试数据
            Map<String, String> testData = createTestData();
            
            // 读取规则文件
            String rules = new String(Files.readAllBytes(Paths.get("rules.txt")));
            System.out.println("Loading rules:\n" + rules);
            
            // 创建词法分析器
            MapDSLLexer lexer = new MapDSLLexer(CharStreams.fromString(rules));
            
            // 创建词法符号流
            CommonTokenStream tokens = new CommonTokenStream(lexer);
            
            // 创建语法分析器
            MapDSLParser parser = new MapDSLParser(tokens);
            
            // 获取语法树
            ParseTree tree = parser.program();
            
            // 创建访问者并执行
            MapDSLVisitorImpl visitor = new MapDSLVisitorImpl(testData);
            System.out.println("\nExecuting rules...");
            Object result = visitor.visit(tree);
            
            // 打印执行结果
            System.out.println("\nExecution result: " + result);
            System.out.println("\nFinal data state:");
            testData.forEach((key, value) -> System.out.println(key + " = " + value));
            
        } catch (IOException e) {
            System.err.println("Error reading rules file: " + e.getMessage());
        } catch (Exception e) {
            System.err.println("Error executing DSL: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    private static Map<String, String> createTestData() {
        Map<String, String> data = new HashMap<>();
        
        // 个人信息数据
        data.put("name", "John Doe");
        data.put("age", "25");
        data.put("email", "john.doe@example.com");
        data.put("city", "New York");
        
        // 数值数据
        data.put("score", "85");
        data.put("price", "100");
        
        // 文本数据
        data.put("description", "Hello   World   Test");
        data.put("html_content", "<p>Hello</p><div>World</div>");
        data.put("address", "123 Main St, New York, NY 10001");
        
        // 特殊格式数据
        data.put("phone", "123-456-7890");
        data.put("dirty_text", "Hello!!!...World???");
        
        System.out.println("Initial test data:");
        data.forEach((key, value) -> System.out.println(key + " = " + value));
        System.out.println();
        
        return data;
    }
} 